package animator.phantom.renderer.threedee;

/*
    Copyright Janne Liljeblad

    This file is part of Phantom2D.

    Phantom2D is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Phantom2D is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Phantom2D.  If not, see <http://www.gnu.org/licenses/>.
*/

import animator.phantom.renderer.param.AnimCoords3D;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.Box;
import com.sun.j3d.utils.image.TextureLoader;
import com.sun.j3d.utils.universe.SimpleUniverse;
import com.sun.j3d.utils.universe.MultiTransformGroup;
import javax.imageio.*;
import javax.imageio.stream.*;
import javax.vecmath.*;
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.applet.Applet;
import java.awt.GraphicsConfiguration;
import java.util.Map;
import javax.media.j3d.*;
import javax.vecmath.Point3d;


public class Phantom3DUniverse
{
	private SimpleUniverse universe = null;
	private BranchGroup scene = null;
	private MultiTransformGroup transformsGroup = null;
	private TransformGroup lastTransform = null;
	private Canvas3D offScreenCanvas = null;

	private static double DEFAULT_FIELD_OF_VIEW = 60.0;
	private static final int TRANSFORMS_COUNT = 5;
	private static double PHYSICAL_WIDTH = 0.5;
	
	public Phantom3DUniverse()
	{
		createSceneGraph();
		offScreenCanvas = createOffScreenCanvas();
		universe = new SimpleUniverse( offScreenCanvas );
		universe.getViewingPlatform().setNominalViewingTransform();//move camera back
		universe.addBranchGraph(scene);
		View view = universe.getViewer().getView();
		view.stopView();
	}

	private void createSceneGraph() 
	{
		// Create a structure to contain objects
		scene = new BranchGroup();
		transformsGroup =  new MultiTransformGroup( TRANSFORMS_COUNT );
		lastTransform = transformsGroup.getTransformGroup( TRANSFORMS_COUNT - 1 );
		lastTransform.setCapability( TransformGroup.ALLOW_CHILDREN_EXTEND );
		lastTransform.setCapability( TransformGroup.ALLOW_CHILDREN_WRITE );

		for( int i = 0; i < TRANSFORMS_COUNT; i++ )
			transformsGroup.getTransformGroup( i ).setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE );

		scene.addChild( transformsGroup.getTransformGroup( 0 ) );
	}

	private Canvas3D createOffScreenCanvas() 
	{
		//--- Create off-screen canvas
		GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D();
		template.setDoubleBuffer( GraphicsConfigTemplate3D.UNNECESSARY );
		GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().
						getDefaultScreenDevice().getBestConfiguration( template );

		Canvas3D newOffScreenCanvas = new Canvas3D( gc, true );
		return newOffScreenCanvas;
	}

	public synchronized BufferedImage renderImage( float frameTime, AnimCoords3D coords, Phantom3DCamera camera, Node shape, Dimension screenSize )
	{
		lastTransform.removeAllChildren();

		BranchGroup newBranch = new BranchGroup();
		newBranch.setCapability(BranchGroup.ALLOW_DETACH);
		newBranch.addChild( shape );
		lastTransform.addChild( newBranch );

		doUserTransform( coords, frameTime );

		if( camera != null )
			doCameraTransform( camera.coords, frameTime );
		else
			universe.getViewingPlatform().setNominalViewingTransform();

		View view = universe.getViewer().getView();
		if( camera != null )
			view.setFieldOfView( Math.toRadians( camera.fieldOfView.get( frameTime ) ) );
		else
			view.setFieldOfView( Math.toRadians( DEFAULT_FIELD_OF_VIEW ) );
		view.setSceneAntialiasingEnable( true );

		view.startView();
		BufferedImage frame = renderFrame( screenSize.width, screenSize.height );
		view.stopView();

		return frame;
	}

	private BufferedImage renderFrame( int drawWidth, int drawHeight )
	{
		// set screen size
		Screen3D screen = offScreenCanvas.getScreen3D();
		screen.setSize( drawWidth, drawHeight );

		// Just set physical width and height to match dimensions of rendered image to get square pixels
		screen.setPhysicalScreenWidth( PHYSICAL_WIDTH );
		screen.setPhysicalScreenHeight( PHYSICAL_WIDTH * ((double) drawHeight / (double) drawWidth ));

		BufferedImage drawRaster = new BufferedImage( drawWidth, drawHeight, BufferedImage.TYPE_INT_ARGB );
		ImageComponent2D buffer = new ImageComponent2D( ImageComponent.FORMAT_RGBA, drawRaster, true, true );
		buffer.setCapability( ImageComponent2D.ALLOW_IMAGE_READ );

		offScreenCanvas.setOffScreenBuffer( buffer );
		offScreenCanvas.renderOffScreenBuffer();
		offScreenCanvas.waitForOffScreenRendering();

		return offScreenCanvas.getOffScreenBuffer().getImage();
	}

	//--- THis way too complex i think
	private void doUserTransform( AnimCoords3D coords, float time )
	{
		Transform3D trans = new Transform3D();
		Vector3f moveVec = new Vector3f( coords.x.getValue( time ), coords.y.getValue( time ), coords.z.getValue( time ) );
		trans.setTranslation( moveVec );
		transformsGroup.getTransformGroup( 0 ).setTransform( trans );

		trans = new Transform3D();
		trans.rotX( Math.toRadians( (double) coords.rotation.getValue( time ) ) );
		transformsGroup.getTransformGroup( 1 ).setTransform( trans );

		trans = new Transform3D();
		trans.rotY( Math.toRadians( (double) coords.rotY.getValue( time ) ) );
		transformsGroup.getTransformGroup( 2 ).setTransform( trans );

		trans = new Transform3D();
		trans.rotZ( Math.toRadians( (double) coords.rotZ.getValue( time ) ) );
		transformsGroup.getTransformGroup( 3 ).setTransform( trans );
		
		Vector3d scale = new Vector3d( (double) coords.xScale.getValue( time ) / 100.0,
						(double) coords.yScale.getValue( time ) / 100.0,
						(double) coords.zScale.getValue( time ) / 100.0);
		trans = new Transform3D();
		trans.setScale( scale );
		transformsGroup.getTransformGroup( 4 ).setTransform( trans );
	}

	private void doCameraTransform( AnimCoords3D coords, float time )
	{
		TransformGroup tGroup = universe.getViewingPlatform().getMultiTransformGroup().getTransformGroup(0);
		Transform3D transform = new Transform3D();
		transform.setTranslation( new Vector3f( coords.x.getValue( time ), coords.y.getValue( time ), coords.z.getValue( time ) ) );
		Transform3D rotTrans = new Transform3D();
		rotTrans.rotX( Math.toRadians( (double) coords.rotation.getValue( time ) ) );
		transform.mul( rotTrans );

		rotTrans = new Transform3D();
		rotTrans.rotY( Math.toRadians( (double) coords.rotY.getValue( time ) ) );
		transform.mul( rotTrans );

		rotTrans = new Transform3D();
		rotTrans.rotZ( Math.toRadians( (double) coords.rotZ.getValue( time ) ) );
		transform.mul( rotTrans );
		tGroup.setTransform( transform );
	}

}//end class

/*

Scaling
|x2|   |sx 0 0 0| |x1|
|y2| = |0 sy 0 0|*|y1|
|z2|   |0 0 sz 0| |z1|
|1 |   |0 0 0  1| |1 |

	private Appearance getTexturedAppearance( BufferedImage bImage )
	{
		// Create textured appearance object
		Appearance app = new Appearance();

		int flags = TextureLoader.BY_REFERENCE | TextureLoader.Y_UP;
		flags |= TextureLoader.ALLOW_NON_POWER_OF_TWO;
		flags |= TextureLoader.GENERATE_MIPMAP;

		Texture tex = new TextureLoader( bImage, flags).getTexture();
		tex.setMagFilter(Texture.BASE_LEVEL_LINEAR);
		tex.setMinFilter(Texture.MULTI_LEVEL_LINEAR);

		app.setTexture(tex);
		TextureAttributes texAttr = new TextureAttributes();
		texAttr.setTextureMode(TextureAttributes.MODULATE);
		app.setTextureAttributes(texAttr);

		return app;
	}


		// Create textured cube and add it to the scene graph.
		Appearance app = getTexturedAppearance( getBufferedImageFromFile( testFile ) );
		Box textureCube = new Box(0.4f, 0.4f, 0.4f,
			Box.GENERATE_TEXTURE_COORDS |
			Box.GENERATE_TEXTURE_COORDS_Y_UP, app);
		objTrans.addChild(textureCube);

		// Have Java 3D perform optimizations on this scene graph.
		objRoot.compile();
*/